package server

import (
	"context"
	"fmt"
	"time"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/mount"
	"github.com/docker/go-connections/nat"

	econd "gopkg.openfuyao.cn/bkeadm/pkg/executor/containerd"
	"gopkg.openfuyao.cn/bkeadm/pkg/executor/docker"
	"gopkg.openfuyao.cn/bkeadm/pkg/global"
	"gopkg.openfuyao.cn/bkeadm/pkg/infrastructure"
	"gopkg.openfuyao.cn/bkeadm/utils"
	"gopkg.openfuyao.cn/bkeadm/utils/log"
)

// StartChartRegistry starts the chart repository service.
func StartChartRegistry(name, image, chartRegistryPort, chartDataDirectory string) error {
	var err error
	if infrastructure.IsContainerd() && !infrastructure.IsDocker() {
		return startChartRegistryWithContainerd(name, image, chartRegistryPort, chartDataDirectory)
	}

	if !infrastructure.IsDocker() {
		log.BKEFormat(log.ERROR, "docker or containerd runtime not found.")
		return nil
	}
	err = global.Docker.EnsureImageExists(docker.ImageRef{Image: image},
		utils.NewRetryOptions(utils.MaxRetryCount, utils.DelayTime))
	if err != nil {
		return err
	}
	serverRunFlag, err := global.Docker.EnsureContainerRun(name)
	if err != nil {
		return err
	}
	// 服务已经运行
	if serverRunFlag {
		log.BKEFormat(log.INFO, "The chart warehouse service is already running. ")
		return nil
	}
	// Starting the image repository
	err = global.Docker.Run(
		&container.Config{
			Image: image,
			ExposedPorts: map[nat.Port]struct{}{
				"8080/tcp": {},
			},
			Env: []string{"DEBUG=true", "STORAGE=local", "STORAGE_LOCAL_ROOTDIR=/charts"},
		},
		&container.HostConfig{
			Mounts: []mount.Mount{
				{
					Type:   mount.TypeBind,
					Source: chartDataDirectory,
					Target: "/charts",
				},
			},
			PortBindings: map[nat.Port][]nat.PortBinding{
				nat.Port("8080/tcp"): {
					{HostIP: "0.0.0.0",
						HostPort: chartRegistryPort,
					},
				},
			},
			RestartPolicy: container.RestartPolicy{
				Name:              "always",
				MaximumRetryCount: 0,
			},
		}, nil, nil, name)
	if err != nil {
		log.BKEFormat(log.WARN, "The chart repository service fails to be deployed")
		return err
	}
	client := global.Docker.GetClient()
	for {
		log.BKEFormat(log.INFO, "Wait for the chart mirroring service to start...")
		time.Sleep(5 * time.Second)
		containerInfo, err := client.ContainerInspect(context.Background(), name)
		if err != nil {
			continue
		}
		if containerInfo.ContainerJSONBase == nil {
			continue
		}
		if containerInfo.State.Running {
			break
		}
	}
	log.BKEFormat(log.INFO, "The chart mirroring service is started. ")
	return nil
}

func startChartRegistryWithContainerd(name, image, chartRegistryPort, chartDataDirectory string) error {
	err := econd.EnsureImageExists(image)
	if err != nil {
		return err
	}

	serverRunFlag, err := econd.EnsureContainerRun(name)
	if err != nil {
		return err
	}
	// 服务已经运行
	if serverRunFlag {
		log.BKEFormat(log.INFO, "The chart warehouse service is already running. ")
		return nil
	}
	script := []string{
		"run", "-d", fmt.Sprintf("--name=%s", name),
		"-p", fmt.Sprintf("%s:8080", chartRegistryPort),
		"-e", "DEBUG=true", "-e", "STORAGE=local", "-e", "STORAGE_LOCAL_ROOTDIR=/charts",
		"--restart=always",
		"-v", fmt.Sprintf("%s:/charts", chartDataDirectory),
		image,
	}
	err = econd.Run(script)
	if err != nil {
		log.BKEFormat(log.WARN, "The chart repository service fails to be deployed")
		return err
	}

	for {
		log.BKEFormat(log.INFO, "Wait for the chart mirroring service to start...")
		time.Sleep(5 * time.Second)
		info, err := econd.ContainerInspect(name)
		if err != nil {
			continue
		}
		if info.State.Running {
			break
		}
	}
	log.BKEFormat(log.INFO, "The chart mirroring service is started. ")
	return nil
}

func RemoveChartRegistry(name string) error {
	log.BKEFormat(log.INFO, "Remove the chart repository")
	if infrastructure.IsDocker() {
		for i := 0; i < 2; i++ {
			_ = global.Docker.ContainerRemove(name)
			_, exist := global.Docker.ContainerExists(name)
			if exist {
				time.Sleep(3 * time.Second)
			} else {
				break
			}
		}
		return nil
	}
	if infrastructure.IsContainerd() {
		for i := 0; i < 2; i++ {
			_ = econd.ContainerRemove(name)
			_, exist := econd.ContainerExists(name)
			if exist {
				time.Sleep(3 * time.Second)
			} else {
				break
			}
		}
		return nil
	}
	return nil
}
